<template>
    <el-dialog title="上传文件(组件)" v-dialogDrag :close-on-click-modal="false" modal-append-to-body destroy-on-close
        :visible.sync="visible" width="45%">
        <div class="head" v-if="true">
            <div>存储类型：</div>
            <ec-dict-select v-model="dataForm.storeType" dictType="store_type" placeholder="选择存储类型" :clearable="false" style="width:250px">
            </ec-dict-select>
            <div>存储在不同的存储服务器上</div>
        </div>
        <div class="black height">
            <div class="filespace">
                <div class="filespacehead">文件空间</div>
                <div class="filespacelist">
                    <div v-if="filespacelist.length > 0">
                        <div class="ellipsis item" v-for="(item) in filespacelist" :key="item.value"
                            :class="spaceKey==item.value? 'select' : ''" @click="selectSpace(item)">{{item.label}}
                        </div>
                    </div>
                    <div v-else class="nofilespace">
                        暂无存储控件，<span class="active">新增</span>？
                    </div>
                </div>
            </div>
            <div class="filelistbox">
                <el-upload drag :action="uploadUrl" :headers="headers" multiple :data="dataForm" ref="upload"
                    :auto-upload="true" name="file" :on-error="uploadOnError" :on-progress="uploadOnProgress"
                    :on-change="uploadOnChange" :on-success="uploadOnSuccess" :show-file-list="false">
                    <i class="el-icon-upload"></i>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                </el-upload>

                <div class="filelist">
                    <div v-for="(item,index) in fileList" :key="index" class="file">
                        <div style="width:50px;text-align: center;">
                            <ec-file-img :value="item.name" style="height:30px"></ec-file-img>
                        </div>
                        <div class="filename ellipsis">{{item.name}}</div>
                        <div class="filesize ellipsis">{{item.size}}</div>
                        <div class="fileoperation">
                            <span class=" hover" @click="deleteHandler(item)">删除</span>
                            <span class=" hover" @click="copyHandler(item)">复制地址</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="callback()">确定</el-button>
        </span>
    </el-dialog>
</template>

<script>
    import * as filemanagerService from '@/api/file/filemanager'
    import * as filespaceService from '@/api/file/filespace'
    import util from '@/libs/util'

    export default {
        data() {
            return {
                visible: false,
                fileList: [],
                filespacelist: [],
                dataForm: {
                    fileSpace: '',
                    storeType: 'minio',
                    filePath: ''
                },
                spaceKey: '',
                dataRule: {
                    fileSpace: [{
                        required: true,
                        message: '文件空间主键不能为空',
                        trigger: 'blur'
                    }],
                    storeType: [{
                        required: true,
                        message: '存储类型不能为空',
                        trigger: 'blur'
                    }],
                    filePath: [{
                        required: false,
                        message: '文件路径不能为空',
                        trigger: 'blur'
                    }],
                }
            }
        },
        computed: {
            // 设置请求头
            headers() {
                return {
                    // 设置Content-Type类型为multipart/form-data
                    'ContentType': 'multipart/form-data',
                    // 设置token
                    'Authorization': util.cookies.get('token_type') + " " + util.cookies.get('token')
                }
            },
            // 设置上传地址
            uploadUrl() {
                // baseURL是服务器的路径，也是axios的基本路径
                return process.env.VUE_APP_API + '/fs/local/saveFile'
            }
        },
        methods: {
            // 初始化
            init() {
                this.visible = true
                this.fileList = []
                this.spaceKey = ''
                this.$nextTick(() => {
                    this.getFileSpaceList()
                })
            },
            // 查询文件空间
            getFileSpaceList() {
                filespaceService.getfilespacedict().then(data => {
                    if (data && data.length > 0) {
                        this.filespacelist = data;
                        // 默认选中第一个
                        this.spaceKey = data[0].value
                    this.dataForm.fileSpace = data[0].code
                    }
                }).catch((res) => {});
            },
            // 空间选择
            selectSpace(space) {
                if (space) {
                    this.spaceKey = space.value
                    this.dataForm.fileSpace = space.code
                } else {
                    this.$message.error("文件存储空间信息错误，请选择其他文件存储空间。")
                }
            },
            // 删除上传的附件
            deleteHandler(file) {
                if (file) {
                    this.$confirm("确认删除【" + file.fileName + "】？", "确认信息", {
                        distinguishCancelAndClose: true,
                        confirmButtonText: "删除",
                        cancelButtonText: "取消"
                    }).then(() => {
                        filemanagerService.delfilemanager(file.fileId).then(() => {
                            this.deleteFileArrHandler(file.fileId)
                        });
                    });
                }
            },
            // 删除数组中同名文件
            deleteFileArrHandler(fileId) {
                if (this.fileList.length > 0) {
                    this.fileList.forEach((item, index) => {
                        if (item && item.fileId == fileId) {
                            this.fileList.splice(index, 1);
                        }
                    })
                }
            },
            // 复制
            copyHandler(file) {

                var input = document.createElement("textarea"); // 直接构建input
                let text = "文件名称：[" + file.name + "]\r\n文件地址：[" + file.url + "]";
                input.value = text; // 设置内容
                document.body.appendChild(input); // 添加临时实例
                input.select(); // 选择实例内容
                document.execCommand("Copy"); // 执行复制
                document.body.removeChild(input); // 删除临时实例

                document.execCommand("Copy"); // 执行浏览器复制命令
                this.$message({
                    message: '复制成功',
                    type: 'success'
                });
            },
            // 回调函数
            callback() {
                this.$emit("callback", this.fileList)
                this.visible = false
            },
            uploadOnProgress(e, file) { //开始上传
                // console.log(e.percent, file)
            },
            uploadOnChange(file) {
                // console.log("——————————change——————————")
                // console.log(file)
                if (file.status == 'ready') {
                    // console.log("ready")
                } else if (file.status == 'fail') {
                    this.$message.error("图片上传出错，请刷新重试！")
                }
            },
            uploadOnSuccess(e, file) { //上传附件
                // console.log("——————————success——————————")
                if (e.code == '200') {
                    this.$message.success("上传成功")
                    this.fileList.push(e.data)
                } else {
                    this.$message.success("上传失败")
                }
            },
            uploadOnError(e, file) {
                // console.log("——————————error——————————")
                // console.log(e)
                this.$message.error("图片上传出错，请刷新重试！")
            },
        }
    }
</script>

<style scoped>
    .el-upload__tip {
        font-size: 12px;
    }

    .height {
        height: 500px;
        min-width: 800px;
        display: flex;
    }

    .head {
        height: 60px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding: 0 15px;;
    }

    .filespace {
        width: 200px;
        border-right: 1px dashed #d9d9d9;
        background: rgba(200, 200, 200, 0.3);
    }

    .filespace .filespacehead {
        height: 35px;
        line-height: 35px;
        font-size: 14px;
        text-align: center;
        border-bottom: 1px dashed #d9d9d9;
    }

    .filespace .filespacelist {
        font-size: 14px;
        text-align: center;
        height: 460px;
        overflow-y: auto;
        background: #fbfbfb;
    }

    .filespacelist::-webkit-scrollbar-track-piece {
        /* //滚动条凹槽的颜色，还可以设置边框属性 */
        background-color: #f8f8f8;
    }

    .filespacelist::-webkit-scrollbar {
        /* //滚动条的宽度 */
        width: 9px;
        height: 9px;
    }

    .filespacelist::-webkit-scrollbar-thumb {
        /* //滚动条的设置 */
        background-color: #dddddd;
        background-clip: padding-box;
        min-height: 28px;
    }

    .filespacelist::-webkit-scrollbar-thumb:hover {
        background-color: #bbb;
    }

    .filespace .filespacelist .item {
        height: 35px;
        line-height: 35px;
        padding: 5px 0;
        cursor: pointer;
    }

    .nofilespace {
        height: 100px;
        line-height: 100px;
        margin: 10px;
        border-radius: 10px;
        border: 1px solid rgb(160, 207, 255);
        background: rgb(217, 236, 255);
    }

    .select {
        background: #ecf5ff;
        color: #409eff;
    }

    .filelistbox {
        flex: 1;
        padding: 15px;
        background: rgba(200, 200, 200, 0.3);
    }

    .filelistbox /deep/ .el-upload {
        width: 100% !important;
    }

    .filelistbox /deep/ .el-upload-dragger {
        width: 100% !important;
    }

    .filelist {
        margin-top: 10px;
        height: 275px;
        overflow-y: auto;
    }

    .filelist::-webkit-scrollbar-track-piece {
        /* //滚动条凹槽的颜色，还可以设置边框属性 */
        background-color: #f8f8f8;
    }

    .filelist::-webkit-scrollbar {
        /* //滚动条的宽度 */
        width: 9px;
        height: 9px;
    }

    .filelist::-webkit-scrollbar-thumb {
        /* //滚动条的设置 */
        background-color: #dddddd;
        background-clip: padding-box;
        min-height: 28px;
    }

    .filelist::-webkit-scrollbar-thumb:hover {
        background-color: #bbb;
    }

    .file {
        height: 40px;
        background: #fff;
        margin: 5px 0;
        padding: 5px;
        display: flex;
        flex-wrap: nowrap;
        box-sizing: border-box;
    }

    .filename {
        font-size: 14px;
        height: 30px;
        line-height: 30px;
        color: #555;
        margin-left: 10px;
        width: 300px;
    }

    .filesize {
        font-size: 12px;
        height: 30px;
        line-height: 30px;
        color: #555;
        margin-left: 10px;
        width: 80px;
    }

    .fileoperation {
        display: flex;
        flex-wrap: nowrap;
        justify-content: space-between;
        width: 100px;
        font-size: 12px;
        height: 30px;
        line-height: 30px;
        color: #555;
        margin-left: 10px;
        cursor: pointer;
    }

    .hover:hover {
        color: #409EFF;
    }

    .active {
        color: #409EFF;
        text-decoration: underline;
        cursor: pointer;
    }

    .ellipsis {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
</style>